package com.fjw.controller;

import com.fjw.pojo.Warehouse;
import com.fjw.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/warehouse")
public class WarehouseController {

    @Autowired
    private WarehouseService warehouseService;

    // 获取所有仓库记录
    @GetMapping("/list")
    public List<Warehouse> list() {
        return warehouseService.findAll();
    }

    // 根据 id 获取仓库记录
    @GetMapping("/{id}")
    public Warehouse getById(@PathVariable Integer id) {
        return warehouseService.findById(id);
    }

    // 新增仓库记录
    @PostMapping("/add")
    public String add(@RequestBody Warehouse warehouse) {
        try {
            warehouseService.insert(warehouse);
            return "新增成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "新增失败：" + e.getMessage();
        }
    }

    // 更新仓库记录
    @PutMapping("/update")
    public String update(@RequestBody Warehouse warehouse) {
        try {
            warehouseService.update(warehouse);
            return "更新成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败：" + e.getMessage();
        }
    }

    // 根据 id 删除仓库记录
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id) {
        try {
            warehouseService.deleteById(id);
            return "删除成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败：" + e.getMessage();
        }
    }

    // 进货操作，接收数量参数
    @PutMapping("/addStock/{id}")
    public String addStock(@PathVariable Integer id, @RequestParam int num) {
        try {
            warehouseService.addStock(id, num);
            return "进货成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "进货失败：" + e.getMessage();
        }
    }

    // 出货操作，接收数量参数
    @PutMapping("/reduceStock/{id}")
    public String reduceStock(@PathVariable Integer id, @RequestParam int num) {
        try {
            warehouseService.reduceStock(id, num);
            return "出货成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "出货失败：" + e.getMessage();
        }
    }
}